package com.example.lets;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.gc.materialdesign.widgets.SnackBar;
import com.github.ksoichiro.android.observablescrollview.ObservableListView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.widget.CircleImageView;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;

public class UserPageActivity extends BaseActivity implements ObservableScrollViewCallbacks {

    private static final float MAX_TEXT_SCALE_DELTA = 0.3f;

    private ImageView mImageView;
    private View mOverlayView;
    private View mListBackgroundView;
    private TextView mTitleView;
    private TextView mFollow;
    private TextView mChat;
    private Toolbar mToolbarView;
    private View userPageHeader;
    private View mFollowInfo;
    private View mFollowChat;
    private ObservableListView listView;
    private MyAdapter adapter;
    private CircleImageView mUserImg;
    private CircleImageView mUserImgFrm;
    private int mActionBarSize;
    private int mFlexibleSpaceImageHeight;
    private int mFollowAndNameNegativeMargin;
    private int mFollowMargin;
    public static boolean isBottom;
    private boolean isTransp = true;
    private int page = 0;
    private ArrayList<HashMap<String, Object>> listItem = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_page);

        mFollowAndNameNegativeMargin = getResources().getDimensionPixelSize(R.dimen.follow_and_name_negative_margin);
        mFlexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.flexible_space_image_height_user);

        mActionBarSize = getActionBarSize();
        mImageView = (ImageView) findViewById(R.id.image);
        mOverlayView = findViewById(R.id.overlay);
        ViewHelper.setAlpha(mOverlayView, 0.0f);
        listView = (ObservableListView) findViewById(R.id.list);
        listView.setScrollViewCallbacks(this);

        // toolbar
        mToolbarView = (Toolbar) this.findViewById(R.id.user_toolbar);
        mToolbarView.setTitle(null);
        setSupportActionBar(mToolbarView);
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbarView.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // Set padding view for ListView. This is the flexible space.
        View paddingView = new View(this);
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                mFlexibleSpaceImageHeight - mActionBarSize);
        paddingView.setLayoutParams(lp);

        // This is required to disable header's list selector effect
        paddingView.setClickable(true);

        listView.addHeaderView(paddingView);
        LayoutInflater inflater = getLayoutInflater();
        userPageHeader = inflater.inflate(R.layout.user_page_header, null);
        listView.addHeaderView(userPageHeader);

        listItem = new ArrayList<>();
        adapter = new MyAdapter(this, listItem);
        listView.setAdapter(adapter);

        mTitleView = (TextView) findViewById(R.id.title);
        mTitleView.setText(getIntent().getStringExtra("username"));
        mUserImg = (CircleImageView) findViewById(R.id.user_image);
        mUserImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SnackBar(UserPageActivity.this, "FAB is clicked", null, null).show();
            }
        });
        mUserImgFrm = (CircleImageView) findViewById(R.id.user_image_frame);

        mFollowChat = findViewById(R.id.user_follow_chat_bar);
        mFollowInfo = findViewById(R.id.follow_info);
        mFollow = (TextView) findViewById(R.id.follow);
        mChat = (TextView) findViewById(R.id.chat);
        mFollowMargin = getResources().getDimensionPixelSize(R.dimen.margin_standard);

        mFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final User me = BmobUser.getCurrentUser(UserPageActivity.this, User.class);
                final String id = getIntent().getStringExtra("userid");
                if (me.getObjectId().equals(id)) {
                    new SnackBar(UserPageActivity.this, "您不能关注自己", null, null).show();
                    return;
                }

                BmobQuery<FollowRelation> query = new BmobQuery<FollowRelation>();
                query.addWhereEqualTo("userId", me.getObjectId());
                query.findObjects(UserPageActivity.this, new FindListener<FollowRelation>() {
                    @Override
                    public void onSuccess(List<FollowRelation> list) {
                        if (list.size() == 0) {
                            new SnackBar(UserPageActivity.this,
                                    "您为早期用户，未支持关注功能。已为您开启，请再点击一次。",
                                    null, null).show();
                            FollowRelation r = new FollowRelation();
                            r.setUserId(me.getObjectId());
                            r.save(UserPageActivity.this);
                            return;
                        }
                        final FollowRelation r1 = list.get(0);
                        BmobQuery<User> query = new BmobQuery<User>();
                        query.addWhereRelatedTo("following", new BmobPointer(r1));
                        query.findObjects(UserPageActivity.this, new FindListener<User>() {
                            @Override
                            public void onSuccess(List<User> list) {
                                for (User u : list)
                                    if (u.getObjectId().equals(id)) {
                                        new SnackBar(UserPageActivity.this,
                                                "您已关注此人", null, null).show();
                                        return;
                                    }
                                User user = new User();
                                user.setObjectId(id);
                                BmobRelation following = r1.getFollowing();
                                if (following == null) following = new BmobRelation();
                                following.add(user);
                                r1.setFollowing(following);

                                BmobQuery<FollowRelation> query = new BmobQuery<FollowRelation>();
                                query.addWhereEqualTo("userId", id);
                                query.findObjects(UserPageActivity.this, new FindListener<FollowRelation>() {
                                    @Override
                                    public void onSuccess(List<FollowRelation> list) {
                                        if (list.size() == 0) {
                                            FollowRelation r = new FollowRelation();
                                            r.setUserId(id);
                                            r.save(UserPageActivity.this);
                                            new SnackBar(
                                                    UserPageActivity.this,
                                                    "对方为早期用户，未支持关注功能。已为其开启，请再点击一次。",
                                                    null, null).show();
                                            return;
                                        }
                                        FollowRelation r2 = list.get(0);
                                        BmobRelation follower = r2.getFollower();
                                        if (follower == null) follower = new BmobRelation();
                                        follower.add(me);
                                        r2.setFollower(follower);
                                        r2.update(UserPageActivity.this, new UpdateListener() {
                                            @Override
                                            public void onSuccess() {
                                                r1.update(UserPageActivity.this, new UpdateListener() {
                                                    @Override
                                                    public void onSuccess() {
                                                        new SnackBar(UserPageActivity.this, "关注成功！", null, null).show();
                                                        TextView t = ((TextView) findViewById(R.id.follower_list));
                                                        int num = Integer.parseInt(t.getText().toString()) + 1;
                                                        t.setText("" + num);
                                                    }

                                                    @Override
                                                    public void onFailure(int i, String s) {
                                                        new SnackBar(UserPageActivity.this, "由于某种神秘力量，关注失败了:(",
                                                                null, null).show();
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onFailure(int i, String s) {
                                                new SnackBar(UserPageActivity.this,
                                                        "由于某种神秘力量，关注失败了:(",
                                                        null, null).show();
                                            }
                                        });
                                    }

                                    @Override
                                    public void onError(int i, String s) {
                                        new SnackBar(UserPageActivity.this,
                                                "由于某种神秘力量，关注失败了:(", null, null).show();
                                    }
                                });
                            }

                            @Override
                            public void onError(int i, String s) {
                                new SnackBar(UserPageActivity.this,
                                        "由于某种神秘力量，关注失败了:(", null, null).show();
                            }
                        });
                    }

                    @Override
                    public void onError(int i, String s) {
                        new SnackBar(UserPageActivity.this, "由于某种神秘力量，关注失败了:(",
                                null, null).show();
                    }
                });
            }
        });

        mChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(UserPageActivity.this, ChatActivity.class);
                intent.putExtra("targetId", getIntent().getStringExtra("userid"));
                intent.putExtra("avatar", getIntent().getStringExtra("userpicname"));
                intent.putExtra("nickname",getIntent().getStringExtra("username"));
                startActivity(intent);
            }
        });

        // mListBackgroundView makes ListView's background except header view.
        mListBackgroundView = findViewById(R.id.list_background);

        // 设置用户头像
        // 获取头像文件名
        String fileName = getIntent().getStringExtra("userpicname");

        // 得到文件路径
        String cacheDownloadPath = BmobPro.getInstance(this).getCacheDownloadDir() + "/" + fileName;
        String[] name = fileName.split("\\.");
        String newFileName = name[0] + "_1_200_0_100." + name[1];
        String cacheThumbnailPath = BmobPro.getInstance(this).getCacheThumbnailDir() + "/" + newFileName;

        if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件
            // 直接重新生成缓存
            BmobProFile.getInstance(this).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

                @Override
                public void onSuccess(String thumbnailPath) {
                    Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                    mUserImg.setImageBitmap(bm);
                    mImageView.setImageBitmap(ImageProcessing.doBlur(bm, 20, false));
                }

                @Override
                public void onError(int statuscode, String errormsg) {

                }
            });

//            }

        } else { // 文件不存在需要重新下载

            BmobProFile.getInstance(this).download(fileName, new DownloadListener() {

                @Override
                public void onSuccess(String fullPath) {
                    BmobProFile.getInstance(UserPageActivity.this).getLocalThumbnail(fullPath, 1,
                            new LocalThumbnailListener() {

                                @Override
                                public void onSuccess(String thumbnailPath) {
                                    Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                                    mUserImg.setImageBitmap(bm);
                                    mImageView.setImageBitmap(ImageProcessing.doBlur(bm, 20, false));
                                }

                                @Override
                                public void onError(int statuscode, String errormsg) {

                                }
                            });
                    String str = BmobPro.getInstance(UserPageActivity.this).getCacheDownloadDir();
                    Log.i("bmob", str);
                }

                @Override
                public void onProgress(String localPath, int percent) {
                    Log.i("bmob", "download-->onProgress :" + percent);
                }

                @Override
                public void onError(int statuscode, String errormsg) {

                }
            });
        }

        View followingList = findViewById(R.id.following_btn);
        View followerList = findViewById(R.id.follower_btn);

        followingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("input", getIntent().getStringExtra("userid"));
                intent.putExtra("mode", "following");
                intent.putExtra("title", getIntent().getStringExtra("username") + "关注的人");
                intent.setClass(UserPageActivity.this, UserList.class);
                startActivity(intent);
            }
        });

        followerList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("input", getIntent().getStringExtra("userid"));
                intent.putExtra("mode", "follower");
                intent.putExtra("title", getIntent().getStringExtra("username") + "的粉丝");
                intent.setClass(UserPageActivity.this, UserList.class);
                startActivity(intent);
            }
        });

        // 个人信息填写
        ((TextView) findViewById(R.id.nickname)).setText(getIntent().getStringExtra("username"));
        ((TextView) findViewById(R.id.introduction)).setText(getIntent().getStringExtra("userdescription"));

        FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        p.setMargins(0, mActionBarSize, 0, 0);
        listView.setLayoutParams(p);

        mUserImg.bringToFront();
        mTitleView.bringToFront();
    }

    public void loadActivities(final LoadActListener listener) {
        BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();
        query.addWhereEqualTo("sponsorId", getIntent().getStringExtra("userid"));
        query.order("createdAt");
        query.setLimit(15);
        query.setSkip(page * 15);
        query.findObjects(this, new FindListener<UserActivity>() {
            @Override
            public void onSuccess(List<UserActivity> list) {
                page++;
                if (listener == null) listItem = new ArrayList<>();

                for (UserActivity activity : list) {
                    HashMap<String, Object> map = new HashMap<>();

                    int dateLength = activity.getStartTime().getDate().length();
                    Double dis = HomeActivity.curLoc.distanceInKilometersTo(activity.getGpsAdd());
                    BigDecimal b = new BigDecimal(dis);
                    Double _dis = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    map.put("distance", _dis.toString());
                    map.put("ItemSponsor", activity.getSponsorName());
                    map.put("ItemPicFileName", activity.getPicFilename());
                    map.put("ItemTitle", activity.getName());
                    map.put("ItemText", activity.getDescription());
                    map.put("number", activity.getPeopleNumber());
                    map.put("sponsorId", activity.getSponsorId());
                    map.put("place", activity.getPlace());
                    map.put("detail", activity.getDetailPlace());
                    map.put("time", activity.getStartTime().getDate().substring(0, dateLength - 3));
                    map.put("type", activity.getType());
                    map.put("id", activity.getObjectId());
                    listItem.add(map);
                }

                if (listener == null) {
                    adapter = new MyAdapter(UserPageActivity.this, listItem);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {

                            if (position < 2) return;
                            position -= 2;

                            String title = (String) listItem.get(position).get("ItemTitle");
                            String description = (String) listItem.get(position).get("ItemText");
                            String picFileName = (String) listItem.get(position).get("ItemPicFileName");
                            String sponsorId = (String) listItem.get(position).get("sponsorId");
                            String type = (String) listItem.get(position).get("type");
                            String place = (String) listItem.get(position).get("place");
                            String time = (String) listItem.get(position).get("time");
                            String actiId = (String) listItem.get(position).get("id");
                            String detail = (String) listItem.get(position).get("detail");

                            Intent intent = new Intent(UserPageActivity.this, EventActivity.class);
                            intent.putExtra("title", title);
                            intent.putExtra("description", description);
                            intent.putExtra("picFileName", picFileName);
                            intent.putExtra("sponsorId", sponsorId);
                            intent.putExtra("place", place);
                            intent.putExtra("detail", detail);
                            intent.putExtra("time", time);
                            intent.putExtra("type", type);
                            intent.putExtra("id", actiId);

                            startActivity(intent);
                        }
                    });
                } else {
                    adapter.notifyDataSetChanged();
                    listener.loadFinish(list.size() == 0 ? LoadMoreActLayout.NOMORE :
                            LoadMoreActLayout.SUCCEED, list.size());
                }
            }

            @Override
            public void onError(int i, String s) {
                listener.loadFinish(LoadMoreActLayout.FAIL, 0);
                new SnackBar(UserPageActivity.this, "下载失败，网络异常！", null, null).show();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();

        LoadActivityTask task = new LoadActivityTask(this, null);
        task.execute();

        // 个人信息填写
        BmobQuery<User> query = new BmobQuery<>();
        query.getObject(this, getIntent().getStringExtra("userid"), new GetListener<User>() {
            @Override
            public void onSuccess(User user) {
                List<String> tagList = new ArrayList<>();
                if (user.getTag1() != null && !user.getTag1().equals(""))
                    tagList.add(user.getTag1());
                if (user.getTag2() != null && !user.getTag2().equals(""))
                    tagList.add(user.getTag2());
                if (user.getTag3() != null && !user.getTag3().equals(""))
                    tagList.add(user.getTag3());
                String tag = "";
                for (int i = 0; i < tagList.size(); i++) {
                    tag += tagList.get(i);
                    if (i != tagList.size() - 1) tag += ", ";
                }
                if (tag.equals("")) tag = "无";
                ((TextView) findViewById(R.id.tag)).setText(tag);

                ((TextView) findViewById(R.id.gender)).setText(
                        user.getGender().equals("male") ? "男" : "女");
                ((TextView) findViewById(R.id.age)).setText(user.getAge().toString());
                ((TextView) findViewById(R.id.num_of_activity)).setText(
                        user.getSponsornum() == null ? "(0)" : "(" + user.getSponsornum().toString() + ")");
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });

        BmobQuery<FollowRelation> q = new BmobQuery<>();
        q.addWhereEqualTo("userId", getIntent().getStringExtra("userid"));
        q.findObjects(UserPageActivity.this, new FindListener<FollowRelation>() {
            @Override
            public void onSuccess(List<FollowRelation> list) {
                if (list.size() == 0) return;
                FollowRelation r = list.get(0);
                BmobQuery<User> q = new BmobQuery<>();
                q.addWhereRelatedTo("follower", new BmobPointer(r));
                q.findObjects(UserPageActivity.this, new FindListener<User>() {
                    @Override
                    public void onSuccess(List<User> list) {
                        ((TextView) findViewById(R.id.follower_list)).setText("" + list.size());
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });

                q = new BmobQuery<>();
                q.addWhereRelatedTo("following", new BmobPointer(r));
                q.findObjects(UserPageActivity.this, new FindListener<User>() {
                    @Override
                    public void onSuccess(List<User> list) {
                        ((TextView) findViewById(R.id.follow_list)).setText("" + list.size());
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {

        if (listView.getCount() == 0) isBottom = true;
        else if (listView.getLastVisiblePosition() == listView.getCount() - 1) {
            int lastIndex = listView.getLastVisiblePosition() - listView.getFirstVisiblePosition();
            View lastItem = listView.getChildAt(lastIndex);
            int height = lastItem.getMeasuredHeight();
            int location[] = new int[2];
            lastItem.getLocationInWindow(location);
            int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
            isBottom = location[1] <= screenHeight - height;
        } else isBottom = false;

        if (scrollY > mFlexibleSpaceImageHeight - mActionBarSize) {
            if (isTransp) {
                ViewPropertyAnimator.animate(mOverlayView).cancel();
                ViewPropertyAnimator.animate(mOverlayView).alpha(1.0f).setDuration(200).start();
                findViewById(R.id.user_toolbar).setBackgroundColor(Color.rgb(0x3F, 0x51, 0xB5));
                ((Toolbar) findViewById(R.id.user_toolbar)).setTitle(getIntent().getStringExtra("username"));
                isTransp = false;
            }

            mFollowChat.setVisibility(View.INVISIBLE);
        } else if (!isTransp) {
            ViewPropertyAnimator.animate(mOverlayView).cancel();
            ViewPropertyAnimator.animate(mOverlayView).alpha(0.0f).setDuration(200).start();
            findViewById(R.id.user_toolbar).setBackgroundColor(Color.TRANSPARENT);
            ((Toolbar) findViewById(R.id.user_toolbar)).setTitle(null);

            isTransp = true;
            mFollowChat.setVisibility(View.VISIBLE);
        } else {
            ((Toolbar) findViewById(R.id.user_toolbar)).setTitle(null);
            mFollowChat.setVisibility(View.VISIBLE);
        }

        // Translate overlay and image
        float flexibleRange = mFlexibleSpaceImageHeight - mActionBarSize;
        int minOverlayTransitionY = mActionBarSize - mOverlayView.getHeight();
        ViewHelper.setTranslationY(mOverlayView, ScrollUtils.getFloat(-scrollY, minOverlayTransitionY, 0));
        ViewHelper.setTranslationY(mImageView, ScrollUtils.getFloat(-scrollY / 2, minOverlayTransitionY, 0));

        // Translate list background
        ViewHelper.setTranslationY(mListBackgroundView, Math.max(0, -scrollY + mFlexibleSpaceImageHeight));

        // Translate FAB & USERIMGE
        int maxFabTranslationY = mFlexibleSpaceImageHeight - mFollow.getHeight() / 2;
        int maxImgTranslationY = mFlexibleSpaceImageHeight - mUserImg.getHeight() / 2;
        float fabTranslationY = ScrollUtils.getFloat(
                -scrollY + mFlexibleSpaceImageHeight - mFollow.getHeight() / 2,
                mActionBarSize - mFollow.getHeight() / 2,
                maxFabTranslationY);
        float imgTranslationY = ScrollUtils.getFloat(
                -scrollY + mFlexibleSpaceImageHeight - mUserImg.getHeight() / 2,
                mActionBarSize - mUserImg.getHeight() / 2,
                maxImgTranslationY) - mFlexibleSpaceImageHeight / 5 * 3;
        float frmTranslationY = ScrollUtils.getFloat(
                -scrollY + mFlexibleSpaceImageHeight - mUserImgFrm.getHeight() / 2,
                mActionBarSize - mUserImgFrm.getHeight() / 2,
                maxImgTranslationY) - mFlexibleSpaceImageHeight / 5 * 3;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            // On pre-honeycomb, ViewHelper.setTranslationX/Y does not set margin,
            // which causes FAB's OnClickListener not working.
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mFollow.getLayoutParams();
            lp.leftMargin = mOverlayView.getWidth() - mFollowMargin - mFollow.getWidth();
            lp.topMargin = (int) fabTranslationY;
            mUserImg.requestLayout();
            mUserImgFrm.requestLayout();
        } else {
            ViewHelper.setTranslationX(mUserImg, mOverlayView.getWidth() / 2 - mUserImg.getWidth() / 2);
            ViewHelper.setTranslationY(mUserImg, imgTranslationY);
            ViewHelper.setTranslationX(mUserImgFrm, mOverlayView.getWidth() / 2 - mUserImgFrm.getWidth() / 2);
            ViewHelper.setTranslationY(mUserImgFrm, frmTranslationY);
        }

        // Translate title text
        Log.i("user_page", "y = " + mTitleView.getY());

        int titleTranslationY = (int) (mUserImgFrm.getMeasuredHeight() + mUserImgFrm.getY());
        ViewHelper.setTranslationY(mTitleView, titleTranslationY);
        ViewHelper.setTranslationY(mFollowInfo, titleTranslationY + mTitleView.getMeasuredHeight()
                - mFollowAndNameNegativeMargin);
        ViewHelper.setTranslationY(mFollowChat, mOverlayView.getY() + mOverlayView.getMeasuredHeight()
                - mFollowChat.getMeasuredHeight());

    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void setPivotXToTitle() {
        Configuration config = getResources().getConfiguration();
        if (Build.VERSION_CODES.JELLY_BEAN_MR1 <= Build.VERSION.SDK_INT
                && config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            ViewHelper.setPivotX(mTitleView, findViewById(android.R.id.content).getWidth());
        } else {
            ViewHelper.setPivotX(mTitleView, mOverlayView.getWidth() / 2 - mUserImg.getWidth() / 2);
        }
    }

    class LoadActivityTask extends AsyncTask<Void, Integer, Integer> {

        private Context context;
        private LoadActListener listener;

        public LoadActivityTask(Context context, LoadActListener listener) {
            this.context = context;
            this.listener = listener;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            BmobQuery<UserActivity> query = new BmobQuery<>();
            query.addWhereEqualTo("sponsorId", getIntent().getStringExtra("userid"));
            query.order("createdAt");
            query.setLimit(15);
            query.findObjects(context, new FindListener<UserActivity>() {
                @Override
                public void onSuccess(List<UserActivity> list) {
                    page++;
                    if (listener == null) listItem = new ArrayList<>();

                    for (UserActivity activity : list) {
                        HashMap<String, Object> map = new HashMap<>();

                        int dateLength = activity.getStartTime().getDate().length();
                        Double dis = HomeActivity.curLoc.distanceInKilometersTo(activity.getGpsAdd());
                        BigDecimal b = new BigDecimal(dis);
                        Double _dis = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                        map.put("distance", _dis.toString());
                        map.put("ItemSponsor", activity.getSponsorName());
                        map.put("ItemPicFileName", activity.getPicFilename());
                        map.put("ItemTitle", activity.getName());
                        map.put("ItemText", activity.getDescription());
                        map.put("number", activity.getPeopleNumber());
                        map.put("sponsorId", activity.getSponsorId());
                        map.put("place", activity.getPlace());
                        map.put("detail", activity.getDetailPlace());
                        map.put("time", activity.getStartTime().getDate().substring(0, dateLength - 3));
                        map.put("type", activity.getType());
                        map.put("id", activity.getObjectId());
                        listItem.add(map);
                    }

                    if (listener == null) {
                        adapter = new MyAdapter(UserPageActivity.this, listItem);
                        listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {

                                if (position < 2) return;
                                position -= 2;

                                String title = (String) listItem.get(position).get("ItemTitle");
                                String description = (String) listItem.get(position).get("ItemText");
                                String picFileName = (String) listItem.get(position).get("ItemPicFileName");
                                String sponsorId = (String) listItem.get(position).get("sponsorId");
                                String type = (String) listItem.get(position).get("type");
                                String place = (String) listItem.get(position).get("place");
                                String detail = (String) listItem.get(position).get("detail");
                                String time = (String) listItem.get(position).get("time");
                                String actiId = (String) listItem.get(position).get("id");

                                Intent intent = new Intent(UserPageActivity.this, EventActivity.class);
                                intent.putExtra("title", title);
                                intent.putExtra("description", description);
                                intent.putExtra("picFileName", picFileName);
                                intent.putExtra("sponsorId", sponsorId);
                                intent.putExtra("place", place);
                                intent.putExtra("detail", detail);
                                intent.putExtra("time", time);
                                intent.putExtra("type", type);
                                intent.putExtra("id", actiId);

                                startActivity(intent);
                            }
                        });
                    } else {
                        adapter.notifyDataSetChanged();
                        listener.loadFinish(list.size() == 0 ? LoadMoreActLayout.NOMORE :
                                LoadMoreActLayout.SUCCEED, list.size());
                    }
                }

                @Override
                public void onError(int i, String s) {
                    listener.loadFinish(LoadMoreActLayout.FAIL, 0);
                    new SnackBar(UserPageActivity.this, "下载失败，网络异常！", null, null).show();
                }
            });
            return null;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
}

interface OnLoadActListener {

    void onRefresh(LoadMoreActLayout loadMoreActLayout);

    /**
     * 加载操作
     */
    void onLoadMore(LoadMoreActLayout loadMoreActLayout);
}

class LoadActListener implements OnLoadActListener {

    private Context mContext;
    private LoadMoreActLayout loadMoreActLayout;

    public LoadActListener(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void onRefresh(final LoadMoreActLayout loadMoreActLayout) {

    }

    @Override
    public void onLoadMore(LoadMoreActLayout loadMoreActLayout) {
        this.loadMoreActLayout = loadMoreActLayout;
        ((UserPageActivity) mContext).loadActivities(this);
    }

    public void loadFinish(int code, int num) {
        loadMoreActLayout.loadmoreFinish(code, num);
    }
}
